/*
 * Copyright (c) 2016. For Intelligent Group.
 */

package com.intelligent.mts.da.handler;


import com.intelligent.mts.core.utils.AppConst;
import com.intelligent.mts.da.message.ReceiveMessage;
import com.intelligent.mts.da.utils.MessageUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Created by Julia.Zhou on 2016/07/20.
 */
public class   AdapterHandler extends ChannelInboundHandlerAdapter {

	public static Logger logger = LoggerFactory.getLogger(AdapterHandler.class);

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		String clientIp = ctx.channel().remoteAddress().toString();
		logger.info("Received message from [{}], body:[{}]",clientIp, msg);
		String returnMessage = "";

		ReceiveMessage receiveMessage = MessageUtils.decodeMessage((String) msg);
		logger.debug("message:{}", receiveMessage);
		if (receiveMessage == null) {
			logger.error("The message is empty.");
            return;
		}

		String startFlag = receiveMessage.getStartFlag();
		ChannelPipeline p = ctx.pipeline();
		this.clearPipeline(p);
		switch(startFlag) {
			case AppConst.START_VALIDATE_REQ :
				p.addAfter("AdapterHandler","validateHandler", new ValidateHandler());
				ctx.fireChannelRead(receiveMessage);
				break;
			case AppConst.START_STATUS_REQ:
				p.addAfter("AdapterHandler","updateStatusHandler", new UpdateStatusHandler());
				ctx.fireChannelRead(receiveMessage);
				break;
			case AppConst.START_DATA_REQ :
				p.addAfter("AdapterHandler","saveDataHandler", new SaveDataHandler());
				ctx.fireChannelRead(receiveMessage);
				break;
			case AppConst.START_OFFLINE_REQ :
				p.addAfter("AdapterHandler","saveOfflineDataHandler", new SaveOffLineDataHandler());
				ctx.fireChannelRead(receiveMessage);
				break;
			case AppConst.START_HEARTBEAT :
				p.addAfter("AdapterHandler","heartbeatHandler", new HeartbeatHandler());
				ctx.fireChannelRead(receiveMessage);
				break;
		}
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		super.channelReadComplete(ctx);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		logger.warn("Unexpected exception from com.intelligent.mts.da.handler " + cause);
		ctx.fireExceptionCaught(cause);
	}

	private void clearPipeline(ChannelPipeline p)
	{
		if (p.get("validateHandler") != null) {
			p.remove("validateHandler");
		}
		if (p.get("updateStatusHandler") != null) {
			p.remove("updateStatusHandler");
		}
		if (p.get("saveDataHandler") != null) {
			p.remove("saveDataHandler");
		}
		if (p.get("saveOfflineDataHandler") != null) {
			p.remove("saveOfflineDataHandler");
		}

		if (p.get("heartbeatHandler") != null) {
			p.remove("heartbeatHandler");
		}
	}

}
